/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 短信签名设置
 *  */
import React, { Component } from 'react'
import { Alert, Form, Input, Button, Select, Modal, message } from 'antd'
import { connect } from 'dva'
import BrandSelect from './BrandSelect'
import { debounce } from 'lodash'

const FormItem = Form.Item
const { Option } = Select
const reviewStatus = {
  apply: "审核中...",
  reject: "未通过",
  approved: "已通过",
}

@connect(({ loading, messageSignature }) => ({
  messageSignature,
  submitLoading: loading.effects["messageSignature/setSignConfig"],
  loading: loading.effects["messageSignature/getSignConfig"],
}))
@Form.create()
export default class MessageSignature extends Component {
  state = {
    ssid: "",
    type: '1',         //1：系统签名，2：自定义签名
    usage: '1',        //1：默认使用，2：强制使用
    sign: "",          //自定义签名
    sysSign: "快宝驿站",  //系统签名
    status: "approved",   //审核状态
    editable: false
  }

  componentDidMount() {
    const { dispatch } = this.props
    dispatch({ type: "messageSignature/getSysSignList" })
    this.getList()
  }

  onModalCancle = type => {
    const { dispatch } = this.props
    dispatch({
      type: "messageSignature/setSignConfig",
      payload: {
        type: 1,
        sign: "快宝驿站",
        usage: 1
      }
    }).then(()=>{
      this.getList()
    })
  }
  
  getList() {
    const { dispatch } = this.props
    dispatch({
      type: "messageSignature/getSignConfig"
    }).then(res => {
      const { data } = res
      const { ssid, type, sign, usage, status } = data
      if( status == 'reject' ){
        this.setState({
          ssid,
          type: "1",
          sign: "快宝驿站",
          sysSign: "快宝驿站",
          usage: "1",
          status: status
        })
        type == 2 && Modal.error({
          content: `自定义签名“${sign}”审核失败，将自动为您设置为默认签名设置！`,
          onCancel: ()=>this.onModalCancle(type),
          onOk: ()=>this.onModalCancle(type),
        })        
      }else{
        if( type == 1){
          this.setState({ //自定义与系统签名需分开存放，以免造成数据切换带来的BUG
            sysSign: sign ? sign : '快宝驿站'
          })
        }else if( type == 2 ) {
          this.setState({
            sign
          })
        }else{
          this.setState({
            sysSign: "快宝驿站"
          })
        }
        this.setState({
          ssid,   //系统签名id
          type: type ? type : "1",
          usage: usage ? usage : "1",
          status: status || "approved"  //审核状态（默认通过）
        })
      }
    })
  }

  onTypeSelect = value => {
    const { usage, sysSign } = this.state
    this.setState({ type: value })
    if( value == 1 && usage == 1 && !sysSign){
      this.setSignValue("快宝驿站")
    }
  }

  onStatusSelect = value => {
    const { type, sysSign } = this.state
    this.setState({ usage: value })
    if( value == 1 && type == 1 && !sysSign){
      this.setSignValue("快宝驿站")
    }
  }

  toggleEdit = () => {
    const { editable } = this.state
    this.setState({ editable: !editable })
  }

  handleSubmit = debounce(() => {
    const { dispatch, form: { validateFields }, messageSignature: data } = this.props
    const { type, sign, usage } = data.data
    validateFields((err, res) => {
      if (err) return
      if( res.sysSign && res.type == 1 ){
        res.sign = res.sysSign
      }
      if( type == res.type && sign == res.sign && usage == res.usage ){
        this.toggleEdit()
        return
      }
      delete res.sysSign

      dispatch({
        type: "messageSignature/setSignConfig",
        payload: {
          ...res
        }
      }).then((val) => {
        if( val.code == 0 ){
          Modal.success({
            content: `提交成功${(this.state.type == 2 && res.sign != sign) ? "等待客服审核" : ''}！`
          })
        }
        this.getList()
        this.toggleEdit()
      })
    })
  }, 500, {
    leading: true,
    trailing: false
  })

  setSignValue = val => {
    const { setFieldsValue } = this.props.form
    setFieldsValue({
      "sysSign" : val
    })
    this.setState({sysSign:val})
  }

  handleCancle = ()=> {
    const { messageSignature: data, form:{ setFieldsValue } } = this.props
    const { type, sign, usage, status } = data.data
    let signForForm = type == '2' ? sign : ""
    let sysSignForForm = type == "1" ? (sign ? sign : "快宝驿站") : "快宝驿站"
    this.setState({
      editable: false,
      type: type ? type : "1",
      sign: signForForm,
      sysSign: sysSignForForm,
      usage: usage ? usage : "1",
      status: status ? status : "approved",
    },()=>{
      setFieldsValue({
        "type" : type ? type : "1" ,
        "usage" : usage ? usage : "1" ,
      })
      //防止设置未被渲染的表单域所带来的警告
      if( type == 1 || !type ){
        setFieldsValue({
          "sysSign": sysSignForForm
        })
      }else{
        setFieldsValue({
          "sign" : signForForm
        })
      }
    })
  }

  render() {
    const {
      form: { getFieldDecorator },
      loading,
      submitLoading,
      messageSignature: { brandList }
    } = this.props

    const { type, editable, sign, sysSign, status, usage } = this.state

    const layout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 8 },
    };

    const tailLayout = {
      wrapperCol: { offset: 8, span: 16 },
    };

    return (
      <div>
        <Alert type="warning" message="填写一个短信签名，系统审核通过后，可以设置下属驿站发短信通知时，强制使用您设置的短信签名" showIcon />
        <Form
          {...layout}
          name="basic"
          style={{ marginTop: 24 }}
        >
          <FormItem label="签名类型">
            {
              getFieldDecorator("type", {
                initialValue: type
              })(
                <Select disabled={!editable} onChange={this.onTypeSelect}>
                  <Option key={'1'} value={'1'}>系统签名</Option>
                  <Option key={'2'} value={'2'}>自定义签名</Option>
                </Select>
              )
            }
          </FormItem>
          <FormItem label="短信签名">
            {
              type == "1" ? (
                getFieldDecorator("sysSign", {
                  initialValue: sysSign,
                })(
                  <BrandSelect brandList={brandList} disabled={!editable} setValue={this.setSignValue}/>
                )
              ): (
                getFieldDecorator("sign", {
                  initialValue: sign,
                  rules: [
                    {
                      required: true,
                      message: "请输入短信签名"
                    },
                    {
                      pattern: /^([\u4e00-\u9fa5]|[0-9_a-zA-Z]){1,6}$/,
                      message: '短信签名不超过6个字',
                    },
                  ]
                })(
                  <Input disabled={!editable} placeholder="输入短信签名，不超过6个字" />
                )
              )
            }
          </FormItem>
          <FormItem label="下属驿站使用方式">
            {
              getFieldDecorator("usage", {
                initialValue: usage
              })(
                <Select disabled={!editable} onChange={this.onStatusSelect}>
                  <Option key={'1'} value={'1'}>默认使用，驿站可以更改</Option>
                  <Option key={'2'} value={'2'}>强制使用</Option>
                </Select>
              )
            }
          </FormItem>
          <FormItem {...tailLayout}>
            {
              editable ? (
                <>
                  {
                    type == '1' ?
                      <Button loading={submitLoading} type="primary" onClick={this.handleSubmit}>提交</Button> :
                      <Button loading={submitLoading} type="primary" onClick={this.handleSubmit}>提交审核</Button>
                  }
                  <Button style={{marginLeft: "10px"}} onClick={this.handleCancle}>取消</Button> 
                </>
              ) : (
                  (status == 'approved' || status == 'reject') ? (
                      <Button type="primary" onClick={this.toggleEdit} loading={loading}>修改</Button> 
                  ) : (
                      <Button type="primary" disabled >{reviewStatus[status]}</Button>
                    )
                )
            }
          </FormItem>
        </Form>
      </div>
    )
  }
}